package TCP.oneSent;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/*
* 服务端 TCD
* 一发一收
* */
public class TCPClientDemo2 {
    public static void main(String[] args) throws Exception {
        System.out.println("=====服务端启动=====");
        //1、创建一个TCP服务端的socket对象
        ServerSocket serverSocket = new ServerSocket(8080);
        //2、调用accept方法，阻塞等待客户端连接，一旦客户端连接，就返回一个socket对象
        Socket socket = serverSocket.accept();
        //3、获取输入流，读取数据
        InputStream is = socket.getInputStream();
        //4、把字节输入流封装成特殊数据输入流
        DataInputStream dis = new DataInputStream(is);
        //5、读取数据
        int id = dis.readInt();
        String msg = dis.readUTF();
        System.out.println("id:" + id + "，收到的msg:" + msg);
        //6、获得客户端的ip和端口
        System.out.println("客户端的ip:" + socket.getInetAddress().getHostAddress());
        System.out.println("客户端的端口:" + socket.getPort());
//        socket.close();

        //回复给客户端
        OutputStream os = socket.getOutputStream();
        String replyMsg = "收到";
        os.write(replyMsg.getBytes());

        socket.close();
    }
}
